using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Terra.Core.Infrastructure.Email.Interfaces;
using Terra.Core.Infrastructure.Email.Options;

namespace Terra.Core.Infrastructure.Email.Services;

/// <summary>
/// 使用SMTP发送邮件的服务实现 (支持阿里云邮件推送)
/// </summary>
public class SmtpEmailSender : IEmailSender
{
    private readonly EmailOptions _options;
    private readonly ILogger<SmtpEmailSender> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    public SmtpEmailSender(IOptions<EmailOptions> options, ILogger<SmtpEmailSender> logger)
    {
        _options = options.Value;
        _logger = logger;
    }

    /// <summary>
    /// 发送邮件
    /// </summary>
    public async Task<bool> SendAsync(string to, string subject, string body, bool isHtml = false)
    {
        try
        {
            _logger.LogInformation("准备发送邮件：收件人={To}, 主题={Subject}, 服务器={Server}, 端口={Port}",
                to, subject, _options.SmtpServer, _options.Port);

            // 创建邮件消息
            var mailMessage = new MailMessage();

            // 设置发件人信息
            mailMessage.From = new MailAddress(_options.FromAddress, _options.FromName);
            // 对于阿里云邮件推送，需要设置Sender
            mailMessage.Sender = new MailAddress(_options.FromAddress);

            // 添加收件人
            mailMessage.To.Add(new MailAddress(to));

            // 设置邮件主题
            mailMessage.Subject = subject;

            // 设置邮件内容
            if (isHtml)
            {
                // HTML格式内容
                string plainText = "这是邮件纯文本内容，如果您的邮件客户端不支持HTML格式，将显示此内容。";
                mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainText, null, MediaTypeNames.Text.Plain));
                mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html));
            }
            else
            {
                // 纯文本内容
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = false;
            }

            // 创建SMTP客户端
            using var smtpClient = new SmtpClient(_options.SmtpServer, _options.Port);

            // 如果使用加密连接
            smtpClient.EnableSsl = _options.EnableSsl;

            // 设置凭据
            smtpClient.Credentials = new NetworkCredential(_options.Username, _options.Password);

            // 根据端口选择传输方式
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            // 设置超时时间
            smtpClient.Timeout = 30000; // 30秒

            // 记录更多诊断信息
            _logger.LogInformation("SMTP配置: 服务器={Server}, 端口={Port}, SSL={SSL}, 用户名={Username}",
                _options.SmtpServer, _options.Port, _options.EnableSsl, _options.Username);

            // 发送邮件
            await smtpClient.SendMailAsync(mailMessage);

            _logger.LogInformation("邮件成功发送至 {To}", to);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送邮件至 {To} 失败，详细错误: {Message}", to, ex.Message);

            if (ex.InnerException != null)
            {
                _logger.LogError("内部异常: {InnerMessage}", ex.InnerException.Message);
            }

            return false;
        }
    }
}